package com.wen.imagezip.controller;

import com.wen.imagezip.service.ImageProcessingService;
import com.wen.imagezip.util.ImageCompressionUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
public class ImageUploadController {

    private final ImageProcessingService imageProcessingService;

    public ImageUploadController(ImageProcessingService imageProcessingService) {
        this.imageProcessingService = imageProcessingService;
    }

    /**
     * 图片上传接口
     *
     * @param file 上传的图片文件
     * @return 响应结果
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 处理图片
        byte[] compressedImageBytes = imageProcessingService.processImage(file).join();

        // 保存压缩后的图片到本地 resources/output 文件夹
        String outputFilePath = "src/main/resources/output/" + generateUniqueFileName(file.getOriginalFilename());
        saveImageToFile(compressedImageBytes, outputFilePath);

        return ResponseEntity.ok("Image uploaded and compressed successfully. Output file path: " + outputFilePath);
    }

    /**
     * 测试图片压缩功能
     *
     * @return 响应结果
     * @throws IOException
     */
    @GetMapping("/test-compress")
    public ResponseEntity<String> testImageCompression() throws IOException {
        // 待压缩图片路径
        String inputImagePath = "src/main/resources/input/含英关底图完稿.png"; // 请将此路径替换为实际的待压缩图片路径
        File inputFile = new File(inputImagePath);

        if (!inputFile.exists()) {
            return ResponseEntity.badRequest().body("Test image not found at specified path");
        }

        // 读取待压缩图片
        BufferedImage image = ImageIO.read(inputFile);

        // 动态计算压缩质量
        float compressionQuality = ImageCompressionUtil.dynamicCalculateCompressionQuality(image);

        // 压缩图片
        byte[] compressedImageBytes = ImageCompressionUtil.compressImage(ImageIO.read(inputFile), compressionQuality);

        // 保存压缩后的图片到本地 resources/output 文件夹
        String outputFilePath = "src/main/resources/output/" + generateUniqueFileName("compressed_test_image.jpg");
        saveImageToFile(compressedImageBytes, outputFilePath);

        return ResponseEntity.ok("Test image compressed successfully. Output file path: " + outputFilePath);
    }

    /**
     * 生成唯一的文件名
     *
     * @param originalFileName 原始文件名
     * @return 唯一的文件名
     */
    private String generateUniqueFileName(String originalFileName) {
        String fileName = originalFileName.substring(0, originalFileName.lastIndexOf('.'));
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        return fileName + "_" + System.currentTimeMillis() + fileExtension;
    }

    /**
     * 将图片字节数组保存到文件
     *
     * @param imageBytes 图片字节数组
     * @param filePath 文件路径
     * @throws IOException
     */
    private void saveImageToFile(byte[] imageBytes, String filePath) throws IOException {
        File outputFile = new File(filePath);
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(outputFile);
        fos.write(imageBytes);
        fos.close();
    }
}
